
class HandleRepeatClass {
    constructor(fn, delay = 1000) {
        this.fn = fn;
        this.delay = delay
        this.lastCall = 0;
        this.context = null
    }

    throttle() {
        const _this = this
        return function(...args) {
            const now = Date.now();
            if (now - _this.lastCall >= _this.delay) {
                _this.lastCall = now;
                _this.fn(...args)
            }
        }
    }

}


function getThrottle( fn, wait = 1000) {
   return new HandleRepeatClass(fn, wait).throttle()
}

/**
 * 根据网络地址下载文件
 * @param url
 * @param name 可以不传，不传为地址名称
 * @param type 可以不传，不传为地址类型
 */
const downloadFile = (url, name, type) => {
    const link = document.createElement('a');
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function () {
        const blob = new Blob([xhr.response], {type: 'application/octet-stream'});
        link.href = window.URL.createObjectURL(blob);
        link.style.display = 'none';
        const linkName = url.substring(url.lastIndexOf('/') + 1);
        link.download = name && type ? `${name}.${type}` : linkName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        // 释放临时的对象 URL
        window.URL.revokeObjectURL(link.href);
    }
    xhr.onerror = (err) => {
        console.log(err)
    }
    xhr.send();
}

export {
    getThrottle,
    downloadFile
}
